//
//  UIWebView+JavaScriptAlert.m
//  KidReading
//
//  Created by Telen on 2017/4/21.
//  Copyright © 2017年 刘赞黄Telen. All rights reserved.
//

#import "UIWebView+JavaScriptAlert.h"
#import "UIAlertView+TLBlock.h"

@implementation UIWebView (JavaScriptAlert)

-(void)webView:(UIWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame
{
    [UIAlertView tl_showTitle:@"" message:message didClick:nil buttonTitles:NSLocalizedString(@"Sure", nil),nil];
}

static BOOL diagStat = NO;
static NSInteger btIndex = -1;// 区别于 alert 消失是的按钮
- (BOOL)webView:(UIWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame
{
    [UIAlertView tl_showTitle:@"" message:message didClick:^(UIAlertView * _Nullable alertView, NSInteger buttonIndex) {
        if (buttonIndex == 1) {
            btIndex = 1;
        }else{
            btIndex = 0;
        }
    } buttonTitles:NSLocalizedString(@"Cancel", nil),NSLocalizedString(@"Sure", nil),nil];
    
    btIndex = -1;
    //
    while (btIndex==-1){
        [[NSRunLoop mainRunLoop] runUntilDate:[NSDate distantPast]];
    }
    //
    if (btIndex == 0){//取消;
        diagStat = NO;
    }
    else if (btIndex == 1){//确定;
        diagStat = YES;
    }
    return diagStat;
}

@end


@implementation UIWebView (UserAgentDefine)

+ (void)addUserAgent_Once:(NSString *)defineInfo
{
    if (defineInfo) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectZero];
            NSString* secretAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
            NSString *newUagent = [NSString stringWithFormat:@"%@ %@",secretAgent,defineInfo];
            NSDictionary *dictionary = [[NSDictionary alloc]
                                        initWithObjectsAndKeys:newUagent, @"UserAgent", nil,nil];
            [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
        });
    }
}

@end
